<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/10/17
 * Time: 15:07
 */
namespace App\Http\Admin\Category\Controllers;

use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Website\Models\Menu;
use App\Eloquent\Ygt\Category;

class IndexController extends Controller
{
    /**
     * 首页
     * @author Sojo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getCategoryList()
    {

//        $permission = new Category();
//        dd($permission->getCategoryOption());


        if (request()->isMethod('post')) {
//            return json_encode(array(array('id'=>1,'name'=>'aaa','display_name'=>'bbb','description'=>'ccc')));
            $adminUser          = request()->user('admin')->toArray();
            $company_id         = $adminUser['company_id'];
            $permission = new Category();
            $roleList = $permission->getCategoryList($company_id);
            $roleList->transform(function ($item, $key) {
                $item['image_path'] = asset('storage/upload/'.$item['image_path']);
                return $item;
            });

//            dd($roleList);
            return $roleList->toJson();
        }
        return $this->view('list');

    }

    public function saveCategory()
    {
        $params = $this->requestJson();
        $data = [
            'pid' => isset($params['pid']) ? $params['pid'] : '0',
            'display' => isset($params['display']) ? $params['display'] : '1',
            'cat_name' => $params['cat_name'],
            'sort_id' => $params['sort_id'],
        ];
        if($data['pid'] == 0){
            return $this->ajaxFail('不能添加一级分类');
        }
        if(isset($params['id']) and $params['id']){
            $where = ['id'=>$params['id']];
            $category = new Category();
            $result = $category->updateCategory($data, $where);
        }else{

            $adminUser          = request()->user('admin')->toArray();
            $company_id         = $adminUser['company_id'];
            $data['company_id'] = $company_id;
            $category = new Category();
            $result = $category->addCategory($data);
        }
        return $this->jsonReturn($result);
    }

    public function deleteCategory()
    {
        $params = $this->requestJson();
        if (in_array($params['id'], array(1, 2))) {
            return $this->ajaxFail('不能删除一级分类');
        }

        //先删除子分类的ID（暂时只支持2级分类）
        \App\Eloquent\Ygt\Category::where(['pid'=>$params['id']])->delete();

        $category = new Category();
        $result = $category->delCategory($params['id']);
        return $this->jsonReturn($result);

    }

    public function getCategoryOptionList()
    {
        $params = $this->requestJson();
        $pid = isset($params['pid'])?$params['pid']:0;

        $category = new Category();
        $result = $category->getChildrenList($pid);

    }

}